package com.qiye.livevideo.common;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import java.util.List;

/**
 * Created on 2019/4/21.
 *
 * @author meishijun
 */
public interface BaseService<T extends BaseBean, D extends BaseDao<T>> {
    String  ORDER_BY_DESC = "1";
    String  ORDER_BY_ASC = "2";

    /**
     * 初始化Dao
     * @return
     */
    D initDao();

    /**
     * 删除
     * @param t
     * @return
     */
    default int deleteByPrimaryKey(Integer t) {
        D baseDao = this.initDao();
        return baseDao.deleteByPrimaryKey(t);
    }

    /**
     * 插入
     * @param t
     * @return
     */
    default int insert(T t) {
        D baseDao = this.initDao();
        return baseDao.insert(t);
    }

    /**
     * 根据主键查询
     * @param t
     * @return
     */
    default T selectByPrimaryKey(Integer t) {
        D baseDao = this.initDao();
        return baseDao.selectByPrimaryKey(t);
    }

    /**
     * 根据选择条件查询
     * @param t
     * @return
     */
    default List<T> selectByCondition(T t) {
        D baseDao = this.initDao();
        return baseDao.selectByCondition(t);
    }

    /**
     * 根据选择条件查询分页
     * @param t
     * @return
     */
    default BasePageDto selectAllByPaging(T t) {
        D baseDao = this.initDao();
        BasePageDto responseDto = new BasePageDto();
        PageHelper.startPage(t.getPage(), t.getPageSize());
        if(t.getOrderBy()!=null && !t.getOrderBy().isEmpty() && t.getOrderByDesc()!=null && !t.getOrderByDesc().isEmpty()){
            if(t.getOrderByDesc().equals(ORDER_BY_DESC)){
                t.setOrderByString(t.getOrderBy()+" asc");
            }else if(t.getOrderByDesc().equals(ORDER_BY_ASC)){
                t.setOrderByString(t.getOrderBy()+" desc");
            }
        }
        List<T> lists = baseDao.selectAll(t);
        PageInfo<T> pageInfo = new PageInfo(lists);
        responseDto.setList(pageInfo.getList());
        responseDto.setPageNum(pageInfo.getPageNum());
        responseDto.setPages(pageInfo.getPages());
        responseDto.setPageSize(pageInfo.getPageSize());
        responseDto.setSize(pageInfo.getSize());
        responseDto.setTotal(pageInfo.getTotal());
        return responseDto;
    }

    /**
     * 修改
     * @param t
     * @return
     */
    default int update(T t) {
        BaseDao<T> baseDao = this.initDao();
        return baseDao.update(t);
    }

    /**
     * 查询
     * @param t
     * @return
     */
    default List<T> selectAll(T t) {
        BaseDao<T> baseDao = this.initDao();
        return baseDao.selectAll(t);
    }
}
